package cn.uexpo.lhz.common.utils;


import java.io.*;
import java.util.Base64;

/**
 * base64字符串转换成图片
 *
 * @author
 */
public class Base64Util {

//    public static void main(String[] args) {
//        String base64file = "C:\\Users\\Ben\\Documents\\WeChat Files\\mzyg0615\\FileStorage\\File\\2020-04\\Base64Str\\src\\com\\kk\\img\\base64.txt";
// 
//        String base64Str = readBase64FileFromSD(base64file);
//        Base64ToImage(base64Str, "C:\\Users\\Ben\\Documents\\WeChat Files\\mzyg0615\\FileStorage\\File\\2020-04\\Base64Str\\src\\com\\kk\\img\\base.png");
//    }

    /**
     * base64字符串转换成图片
     *
     * @param imgStr      base64字符串
     * @param imgFilePath 图片存放路径
     * @return
     * @author ZHANGJL
     * @dateTime 2018-02-23 14:42:17
     */
    public static boolean Base64ToImage(String imgStr, String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片

        if (imgStr == null) // 图像数据为空
        {
            return false;
        }
        String base64Str = imgStr.replaceAll(" ", "+");

//        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = Base64.getDecoder().decode(base64Str);
//            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String readBase64FileFromSD(String filePath) {


        FileInputStream inStream = null;//只需传文件名
        ByteArrayOutputStream outStream = null;
        try {
            inStream = new FileInputStream(filePath);
            outStream = new ByteArrayOutputStream();//输出到内存
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);//
            }
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }


        byte[] content_byte = outStream.toByteArray();
        String content = new String(content_byte);
        return content;
    }


    public static byte[] correctBase64Str(String srcStr) {



        byte[] desStr = null;
        if (null != srcStr && !"".equals(srcStr)) {
            String base64Str = srcStr.replaceAll(" ", "+");
            desStr = Base64.getDecoder().decode(base64Str);

        }

        return desStr;
    }

    public static void main(String[] args) {
        byte[] bytes = correctBase64Str("123");
        System.out.println(bytes.length);
    }
}
